<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input v-model="listQuery.userName" placeholder="用户名" style="width: 250px;" class="filter-item" @keyup.enter.native="searchList" />
      <el-select v-model="listQuery.role" placeholder="管理类型" clearable class="filter-item" style="width: 150px">
        <el-option v-for="item in roleOptions" :key="item.index" :label="item.value" :value="item.index" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="searchList">
        搜索
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="用户ID" prop="id" align="center" width="100">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="管理单位" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.managerName || '暂无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账号类型" width="150px" align="center">
        <template slot-scope="{row}">
          <el-tag>{{ row.role | typeFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审批域名" min-width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.domainUrl | domainFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.eMail || '暂无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone || '暂无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="edit(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="add-container">
      <el-button type="success" @click="addShow = true">新增账户</el-button>
    </div>

    <el-dialog title="修改账户" :visible.sync="editShow" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="createFormRules" :model="createForm" label-position="right" label-width="100px" style="width: 600px; margin-left:50px;">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="createForm.userName" readonly />
        </el-form-item>
        <el-form-item label="管理单位" prop="realName">
          <el-input v-model="createForm.managerName" />
        </el-form-item>
        <el-form-item label="账户类型" prop="role">
          <el-select v-model="createForm.role" placeholder="账户类型">
            <el-option v-for="(item,index) in roleOptions" :key="index" :label="item.value" :value="item.index" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="eMail">
          <el-input v-model="createForm.eMail" />
        </el-form-item>
        <el-form-item label="手机号" prop="telphone">
          <el-input v-model="createForm.phone" />
        </el-form-item>
        <!-- //子管理员或者类型为'1' -->
        <div v-if="createForm.role===2 || createForm.role==='子管理员' " class="domain-url">
          <el-form-item label="审批域名" prop="domainPre" placeholder="请输入域名头">
            <el-input v-model="createForm.domainPre" />
          </el-form-item>
          <el-divider />
          <el-form-item prop="keywords" label-width="0">
            <el-select v-model="createForm.keywords" multiple placeholder="请选择域名后缀" collapse-tags>
              <el-option v-for="(item,index) in keywordsOptions" :key="index" :label="item.value" :value="item.value" />
            </el-select>
          </el-form-item>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="editShow = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateOrderDetail">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="添加账户" :visible.sync="addShow" :close-on-click-modal="false">
      <el-form ref="createFormRef" :model="createForm" :rules="createFormRules" label-width="100px" class="create-createForm" style="width: 600px; margin-left:50px;">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="createForm.userName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="createForm.password" type="password" show-password autocomplete="off" />
        </el-form-item>
        <el-form-item label="账户类型" prop="role">
          <el-select v-model="createForm.role" placeholder="请选择管理类型">
            <el-option v-for="item in roleOptions" :key="item.index" :label="item.value" :value="item.index" />
          </el-select>
        </el-form-item>
        <el-form-item label="管理单位" prop="managerName">
          <el-input v-model="createForm.managerName" placeholder="请填写联系单位名称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="eMail">
          <el-input v-model="createForm.eMail" placeholder="请填写管理单位邮箱" />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="createForm.phone" placeholder="请填写管理单位手机号" />
        </el-form-item>
        <div v-if="createForm.role===2 || createForm.role==='子管理员'" class="domain-url">
          <el-form-item label="审批域名" prop="domainPre" placeholder="请输入域名头">
            <el-input v-model="createForm.domainPre" />
          </el-form-item>
          <el-divider />
          <el-form-item prop="keywords" label-width="0">
            <el-select v-model="createForm.keywords" multiple placeholder="请选择域名后缀" collapse-tags>
              <el-option v-for="(item,index) in keywordsOptions" :key="index" :label="item.value" :value="item.value" />
            </el-select>
          </el-form-item>
        </div>

        <el-form-item>
          <el-button type="primary" @click="addAdmin('createFormRef')">立即创建</el-button>
          <el-button @click="resetForm('createFormRef')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import { getAdmins } from '@/api/user'
import { addAdmin } from '@/api/user'
import { phoneReg } from '@/utils/validate.js'
import waves from '@/directive/waves' // waves directive

import { renderTime } from '@/utils/util'

const keywordsOptions = [
  { index: 1, value: '.sh.edu.cn' },
  { index: 2, value: '.edu.sh.cn' },
  { index: 3, value: '.shec.edu.cn' }
]
const roleOptions = [
  { index: 1, value: '超级管理员' },
  { index: 2, value: '子管理员' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = roleOptions.reduce((acc, cur) => {
  acc[cur.index] = cur.value
  return acc
}, {})

export default {
  name: 'Orders',
  directives: { waves },
  filters: {
    typeFilter(index) {
      return calendarTypeKeyValue[index]
    },
    domainFilter(domain) {
      // 判断domain的类型
      if (typeof (domain) === 'string') {
        // 用*去全局替换%
        return domain.replace(/%/g, '*')
      } else {
        return '异常'
      }
    }
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      keywordsOptions,
      keywords: '',
      listLoading: true,
      roleOptions,
      listQuery: {
        userName: '',
        role: undefined
      },
      editShow: false, // 编辑表单是否开启
      addShow: false, // 增加账户表单是否开启
      createForm: {
        id: undefined,
        userName: '', // 用户名
        password: '', // 密码
        managerName: '', // 管理单位名称
        eMail: '', // 邮箱
        phone: '', // 手机号
        role: '', // 角色类型,
        domainPre: '',
        keywords: []
      },
      createFormRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        eMail: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        phone: [
          { pattern: phoneReg, message: '请输入正确手机号', trigger: ['blur', 'change'] }
        ],
        domainPre: [
          { required: true, message: '请输入域名头，例如xx-*或者*', trigger: ['blur', 'change'] }
        ],
        keywords: [
          { required: true, message: '请选择域名后缀', trigger: ['blur', 'change'] }
        ],
        role: [
          { required: true, message: '请选择账户类型', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    renderTime,
    // 1：域名 2：邮箱 3：网站4：安全
    getList() {
      this.listLoading = true
      getAdmins(this.listQuery).then(response => {
        this.list = response.data
      })
      this.listLoading = false
    },
    searchList() {
      this.getList()
    },
    edit(row) {
      this.createForm.userName = row.userName
      this.createForm.role = this.roleOptions.find(item => item.index == row.role) ? this.roleOptions.find(item => item.index == row.role).value : ''
      this.createForm.managerName = row.managerName
      this.createForm.eMail = row.eMail
      this.createForm.phone = row.phone
      this.createForm.id = row.id
      let domainUrl
      if (typeof (row.domainUrl) === 'string') {
        domainUrl = row.domainUrl.split(',')
      } else {
        domainUrl = ['异常']
      }
      // 每次编辑的时候初始化
      this.createForm.domainPre = ''
      this.createForm.keywords = []
      domainUrl.forEach(item => {
        // 如果包含%
        if (item.indexOf('%') !== -1) {
          const arr = item.split('%')
          // 为空字符串''则判断是true的，所有要 === ''判断
          this.createForm.domainPre = (arr[0] === '' ? '*' : arr[0])
          // 将后缀名放到数组中
          this.createForm.keywords.push(arr[1])
        }
      })

      this.editShow = true
    },
    // 更新表格内容
    updateOrderDetail() {
      this.addAdmin('dataForm', this.createForm.id)
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    // 增加用户
    addAdmin(formName, id) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let domain = ''
          if (this.createForm.role === 2 || this.createForm.role === '子管理员') {
            const key = this.createForm.keywords
            const pre = this.createForm.domainPre
            for (let i = 0; i < key.length; i++) {
              if (i === key.length - 1) {
                // 全局替换'*'
                domain += (pre === '' ? '%' : pre.replace(/\*/g, '%')) + key[i]
              } else {
                domain += (pre === '' ? '%' : pre.replace(/\*/g, '%')) + key[i] + ','
              }
            }
          }
          if (id) {
            addAdmin({
              userName: this.createForm.userName,
              managerName: this.createForm.managerName,
              eMail: this.createForm.eMail,
              phone: this.createForm.phone,
              role: typeof (this.createForm.role) !== 'number' ? this.roleOptions.find(item => item.value === this.createForm.role).index : this.createForm.role,
              id: id,
              domainUrl: domain
            }).then(res => {
              this.getList()
              this.editShow = false
              this.$message({
                message: '信息更新成功',
                type: 'success',
                duration: 5 * 1000
              })
              this.createForm.userName = ''
              this.createForm.password = ''
              this.createForm.managerName = ''
              this.createForm.eMail = ''
              this.createForm.phone = ''
              this.createForm.role = ''
              this.createForm.domainPre = ''
              this.createForm.keywords = ''
            })
          } else {
            addAdmin({
              userName: this.createForm.userName,
              password: this.createForm.password,
              managerName: this.createForm.managerName,
              eMail: this.createForm.eMail,
              phone: this.createForm.phone,
              role: this.createForm.role,
              // domainUrl: this.createForm.role === 1 ? '' : (this.createForm.domainPre === '' ? '%' : this.createForm.domainPre  + this.createForm.keywords.join(','))
              domainUrl: domain
            }).then(res => {
              this.getList()
              this.addShow = false
              this.$message({
                message: '账户添加成功',
                type: 'success',
                duration: 5 * 1000
              })
              this.createForm.userName = ''
              this.createForm.password = ''
              this.createForm.managerName = ''
              this.createForm.eMail = ''
              this.createForm.phone = ''
              this.createForm.role = ''
              this.createForm.domainPre = ''
              this.createForm.keywords = ''
            })
          }
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
<style lang="scss">
    @import '@/assets/scss/mixin.scss';
    .el-form-item--medium{
      .el-form-item__content{
        display: flex;
        align-items: center;
        .el-input{
          &+.el-button{
            margin-left: 0.625rem;
          }
        }
        .el-button{
          &:not(:first-child){
            margin-left: 0.625rem;
          }
        }
      }
    }
    .add-container{
      padding-top:20px;
    }
    .domain-url{
      >div{
        display: inline-block;
      }
      .el-divider--horizontal{
        vertical-align: baseline;
        width: 13px;
        margin: 0;
      }
    }
</style>
